package com.harmony.fast.rpc.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.harmony.rpc.HarmonyRpc;
import com.harmony.rpc.remote.ProxyRemote;
import com.task.controller.TaskController;
import com.task.controller.annotation.Param;
import com.task.controller.annotation.Parser;
import com.task.controller.annotation.UITask;
import com.task.controller.param.impl.MapParser;
import com.task.controller.trusteeship.TaskRegister;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.window.dialog.ToastDialog;
import ohos.rpc.IRemoteObject;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteObject;

import java.util.HashMap;
import java.util.Map;

public class RemoteService extends Ability implements TaskRegister {

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");

    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    private ProxyRemote proxyRemote;

    @Override
    public void onStart(Intent intent) {
        HiLog.info(LABEL_LOG, "RemoteService::onStart");
        super.onStart(intent);
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.info(LABEL_LOG, "RemoteService::onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.info(LABEL_LOG, "RemoteService::onStop");
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        // 注册开放的功能，被注册的方法，须有此三个注解的任意一个标记：UITask、AsyncTask、CurrentTask
        registerTask(this);
        // 创建远程代理类
        proxyRemote = HarmonyRpc.getInstance().createProxy();
        return proxyRemote;
    }

    @Override
    public void onDisconnect(Intent intent) {
        // 注销开放的功能，被注销的方法为，被此三个注解任意一个标记的方法，UITask、AsyncTask、CurrentTask
        unregister(this);
    }

    /**
     * service中被调用的功能
     *
     * @param message 方法的参数
     */
    @UITask(value = "show/toast", isAsync = true)
    @Parser(cls = MapParser.class)
    private void showToast(@Param(name = "message") String message) {
        new ToastDialog(this).setText(message).show();
        Map<String, Object> map = new HashMap<>();
        map.put("text", message);
        TaskController.getInstance().getControl().execute("set/text", gson.toJson(map), null);
    }
}